package mx.com.sinformex.simbel.pages.admin;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tapestry5.annotations.ApplicationState;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.BeanEditForm;

import mx.com.sinformex.simbel.db.eos.User;
import mx.com.sinformex.simbel.pages.BasicPage;
import mx.com.sinformex.simbel.utils.Session;

/**
 * @author Oscar Ivan Hernandez Ventura [ oscar at sinformex dot com dot mx]
 *
 * @version $ Id : Users.java , v 1.0 10/05/2009 angellore $
 */
public class Users extends BasicPage {
	
	@Persist
	@Property
	private User user;
	
	private final Log log = LogFactory.getLog(getClass());
	
	public List<User> getUsers() {
		return getAdminDataAccess().fetchUsers();
	}
	
	void onActionFromCreate() {
		getSession().setListing(false);
		getSession().setEditing(false);
		getSession().setInserting(true);
		user = new User();
	}
	
	void onActionFromEdit(String username) {
		getSession().setListing(false);
		getSession().setInserting(false);
		getSession().setEditing(true);
		user = getAdminDataAccess().getUser(username, null);
	}
	
	void onValidate() {
		Object o = getAdminDataAccess().getUser(user.getUsername(), null);
		if(o != null) {
			log.error(String.format("The user %s already exist.", user.getUsername()));
			setError(String.format("The user %s already exist.", user.getUsername()));
		}
	}
	
	void onSuccess() {
		if(getError() != null) {
			return;
		}
		if(!getSession().isListing() || user != null) {
			if(getSession().isEditing()) {
				getAdminDataAccess().updateUser(user);
			} else if(getSession().isInserting()) {
				getAdminDataAccess().saveUser(user);
			}
			user = null;
			getSession().setListing(true);
			getSession().setEditing(false);
			getSession().setInserting(false);
		}
	}

}
